package bjut.core.netty;

import bjut.core.factory.SingletonFactory;
import bjut.core.Message.RpcMessage;
import bjut.core.Message.RpcRequest;
import bjut.core.Message.RpcResponse;
import bjut.core.constant.RpcConstant;
import bjut.core.enums.CompressTypeEnum;
import bjut.core.enums.RpcResponseEnum;
import bjut.core.enums.SerializationTypeEnum;
import bjut.core.handler.RpcRequestHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/14 22:43
 */
public class NettyRpcServiceHandler extends ChannelInboundHandlerAdapter {

    private final RpcRequestHandler rpcRequestHandler;

    public NettyRpcServiceHandler() {
        this.rpcRequestHandler = SingletonFactory.getInstance(RpcRequestHandler.class);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        try {
            if (msg instanceof RpcMessage) {

                RpcMessage rpcMessage = (RpcMessage) msg;
                byte messageType = rpcMessage.getMessageType();
                rpcMessage.setCodec(SerializationTypeEnum.HESSIAN.getCode());
                rpcMessage.setCompress(CompressTypeEnum.GZIP.getCode());

                if (messageType == RpcConstant.HEART_REQUEST_TYPE) {
                    rpcMessage.setMessageType(RpcConstant.HEART_RESPONSE_TYPE);
                    rpcMessage.setData(RpcConstant.HEART_RESPONSE_DATA);
                } else {
                    RpcRequest rpcRequest = (RpcRequest) rpcMessage.getData();
                    Object result = rpcRequestHandler.handle(rpcRequest);
                    rpcMessage.setMessageType(RpcConstant.RESPONSE_TYPE);

                    if (ctx.channel().isActive() && ctx.channel().isWritable()) {
                        RpcResponse<Object> rpcResponse = RpcResponse.success(result, rpcRequest.getRequestId());
                        rpcMessage.setData(rpcResponse);
                    } else {
                        RpcResponse<Object> rpcResponse = RpcResponse.fail(RpcResponseEnum.FAIL);
                        rpcMessage.setData(rpcResponse);
                    }
                }
                ctx.writeAndFlush(rpcMessage).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            //防止内存泄漏
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                ctx.close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
